import Toast from 'tdesign-miniprogram/toast/index';
import Dialog from 'tdesign-miniprogram/dialog/index';
import {
  fetchGood
} from '../../../services/good/fetchGood';
import {
  fetchActivityList
} from '../../../services/activity/fetchActivityList';

import {
  cdnBase
} from '../../../config/index';

import {
  http
} from '@/utils/request.js';

const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;
const obj2Params = (obj = {}, encode = false) => {
  const result = [];
  Object.keys(obj).forEach((key) => result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`));

  return result.join('&');
};

Page({
  data: {
    commentsList: [],
    commentsStatistics: {
      badCount: 0,
      commentCount: 0,
      goodCount: 0,
      goodRate: 0,
      hasImageCount: 0,
      middleCount: 0,
    },
    isShowPromotionPop: false,
    activityList: [],
    recLeftImg,
    recRightImg,
    details: {},
    goodsTabArray: [{
        name: '商品',
        value: '', // 空字符串代表置顶
      },
      {
        name: '详情',
        value: 'goods-page',
      },
    ],
    statusOptions: [{
        value: 0,
        label: '在售',
      },
      {
        value: 1,
        label: '售磬',
      },
    ],
    statusMap: {
      0: '在售',
      1: '售罄',
    },
    jumpArray: [{
        title: '修改',
        url: '/pages/compete/goods/goods?type=edit',
        // url: '/pages/publish/publish?type=edit',
        iconName: 'edit',
      },
      // 根据用户要求，小程序内不能删除已发布商品  by qhj  on 20230702
      /**{
        title: '删除',
        url: '/pages/del/index',
        iconName: 'delete',
      },**/
    ],
    isStock: true,
    cartNum: 0,
    soldout: false,
    buttonType: 1,
    buyNum: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isAllSelectedSku: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    operateType: 0,
    selectSkuSellsPrice: 0,
    maxLinePrice: 0,
    minSalePrice: 0,
    maxSalePrice: 0,
    list: [],
    spuId: '',
    navigation: {
      type: 'fraction'
    },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    soldNum: 0, // 已售数量
    isManage: false,
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  toNav(e) {
    const {
      url
    } = e.detail;
    console.log(url)
    if (url.includes('edit')) {
      wx.setStorageSync('isEdit', true);
      wx.setStorageSync('isView', false);
      wx.setStorageSync('info', 'goods');
      wx.setStorageSync('goodsId', e.target.id)
      wx.navigateTo({
        url: `/pages/compete/goods/goods?type=edit`,
      });
      return;
    }
    console.log('view')
    if (url.includes('view')) {
      wx.setStorageSync('isEdit', false);
      wx.setStorageSync('isView', true);
      wx.setStorageSync('info', 'goods');
      wx.setStorageSync('goodsId', e.target.id)
      wx.navigateTo({
        url: `/pages/compete/detail/detail?type=view&id=${this.data.details.id}&status=${this.data.details.status}`,
      });
      return;
    }
    Dialog.confirm({
      content: '确认删除该商品吗?',
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(async () => {
      await http('POST', '/goods/delete', {
        id: e.target.id
      })
      Toast({
        context: this,
        selector: '#t-toast',
        message: '商品删除成功'
      });
      wx.navigateBack();
    });

  },

  showCurImg(e) {
    const {
      index
    } = e.detail;
    const {
      images
    } = this.data.details;
    console.log(index, images)
    wx.previewImage({
      current: images[index],
      urls: images, // 需要预览的图片http链接列表
    });
  },

  onPageScroll({
    scrollTop
  }) {
    const goodsTab = this.selectComponent('#goodsTab');
    goodsTab && goodsTab.onScroll(scrollTop);
  },

  gotoBuy(type) {
    const {
      isAllSelectedSku,
      buyNum
    } = this.data;
    if (!isAllSelectedSku) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
        icon: '',
        duration: 1000,
      });
      return;
    }
    this.handlePopupHide();
    const query = {
      quantity: buyNum,
      storeId: '1',
      spuId: this.data.spuId,
      goodsName: this.data.details.title,
      skuId: type === 1 ? this.data.skuList[0].skuId : this.data.selectItem.skuId,
      available: this.data.details.available,
      price: this.data.details.minSalePrice,
      specInfo: this.data.details.specList?.map((item) => ({
        specTitle: item.title,
        specValue: item.specValueList[0].specValue,
      })),
      primaryImage: this.data.details.primaryImage,
      spuId: this.data.details.spuId,
      thumb: this.data.details.primaryImage,
      title: this.data.details.title,
    };
    let urlQueryStr = obj2Params({
      goodsRequestList: JSON.stringify([query]),
    });
    urlQueryStr = urlQueryStr ? `?${urlQueryStr}` : '';
    const path = `/pages/order/order-confirm/index${urlQueryStr}`;
    wx.navigateTo({
      url: path,
    });
  },

  getDetail(spuId) {
    Promise.all([fetchGood(spuId), fetchActivityList()]).then((res) => {
      const [details, activityList] = res;
      details.title = details.title || details.name
      details.price = details.originalPrice
      details.images = details.imgUrl?.split(',')
      details.primaryImage = details.imageUrl?.split(',')[0]
      details.hasPermission = details.userId == this.data.userId

      const skuArray = [];
      const {
        skuList = [],
          primaryImage = [],
          isPutOnSale = 1,
          minSalePrice = 0,
          maxSalePrice = 0,
          maxLinePrice = 0,
          soldNum
      } = details;
      skuList.forEach((item) => {
        skuArray.push({
          skuId: item.skuId,
          quantity: item.stockInfo ? item.stockInfo.stockQuantity : 0,
          specInfo: item.specInfo,
        });
      });
      const promotionArray = [];

      const newJumpArray = [...this.data.jumpArray]
      console.log(details.userId)
      if (this.data.userId !== details.userId) {
        newJumpArray[0] = {
          title: '查看',
          url: '/pages/compete/goods/goods?type=view',
          iconName: 'edit',
        }
      }

      this.setData({
        details,
        isStock: details.spuStockQuantity > 0,
        maxSalePrice: maxSalePrice ? parseInt(maxSalePrice) : 0,
        maxLinePrice: maxLinePrice ? parseInt(maxLinePrice) : 0,
        minSalePrice: minSalePrice ? parseInt(minSalePrice) : 0,
        list: promotionArray,
        skuArray: skuArray,
        primaryImage,
        soldout: isPutOnSale === 0,
        soldNum,
        jumpArray: newJumpArray
      });
    });
  },

  onLoad(query) {
    const {
      spuId
    } = query;
    const userInfo = wx.getStorageSync('userInfo') || {}
    const userType = userInfo.userType
    const isManage = [0, 2].includes(userType)

    this.setData({
      spuId: spuId,
      isManage,
      userType,
      userInfo,
      userId: userInfo.id
    });
    this.getDetail(spuId);
  },
});